# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  https://gitee.com/autumner/pythoncookbook
@software: PyCharm 
@file: net_jsonrpcserver.py 
@time: 2019/7/12 下午12:16
"""
'''
使用json实现远程方法调用
'''
import json
from multiprocessing.connection import Listener
from threading import Thread

class RPCHandle:
    def __init__(self):
        self._functions = {}

    def register_function(self, func):
        self._functions[func.__name__] = func

    def handle_connection(self, connection):
        try:
            while True:
                func_name, args, kwargs = json.loads(connection.recv())
                try:
                    r = self._functions[func_name](*args, **kwargs)
                    connection.send(json.dumps(r))
                except Exception as e:
                    connection.send(json.dumps(str(e)))
        except EOFError:
            pass

# Create rpc server
def rpc_server(handle, address, authkey):
    sock = Listener(address, authkey=authkey)

    while True:
        client = sock.accept()
        t = Thread(target=handle.handle_connection, args=(client, ))
        t.daemon = True
        t.start()

# Some remote function
def add(x, y):
    return x + y

def sub(x, y):
    return x - y

# Register with a handler
handler = RPCHandle()
handler.register_function(add)
handler.register_function(sub)

# run the server
rpc_server(handler, ('localhost', 17000), authkey=b'peekaboo')
